package org.sample.traffic;

import org.sample.thread.BlockQueue;

import java.util.concurrent.*;

/**
 * Created by alan on 2017/7/11.
 */
public class Road {

    private static final ScheduledExecutorService inPool = Executors.newScheduledThreadPool(10);

    private static final ScheduledExecutorService outPool = Executors.newScheduledThreadPool(10);

    private BlockQueue<String> vehicles = new BlockQueue<>();

    private String name;

    private Lamp lamp;

    public Road(String name, Lamp lamp) {
        this.name = name;
        this.lamp = lamp;

        inPool.scheduleAtFixedRate(() -> {
            vehicles.put(this.name + "_" + ThreadLocalRandom.current().nextInt());
        }, 1, 2, TimeUnit.SECONDS);

        outPool.scheduleAtFixedRate(() -> {
            if (lamp.isLighted()) {
                String car = vehicles.take();
                System.out.println(car + "通过。");
            }
        }, 1, 2, TimeUnit.SECONDS);
    }

}